package org.refresh.injectors.xml;

import java.util.Map;

import org.refresh.injectors.XMLInjector;

/*******************************************************************************
 * Copyright (c) 2005, 2006 Jules White. All rights reserved. This program and
 * the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: Jules White - initial API and implementation
 ******************************************************************************/
public class ReplaceAnnotation extends AbstractAnnotation {

	public static final String TYPE = "replace";

	public ReplaceAnnotation() {
		super(TYPE);
	}

	@Override
	protected String handleImpl(String template, Map options, Map bindings) {
		String with = (String) options.get(XMLInjector.WITH_KEY);
		if (with == null || (options != null && options.size() > 2)) {
			for (Object key : options.keySet()) {
				String target = "" + key;
				String replacementval = "" + options.get(key);
				if(replacementval.equals("${with}")){
					replacementval = with;
				}
				else{
					replacementval = getTemplateInjector().inject(replacementval,
						bindings);
				}
				String replaceex = "";
				boolean inelement = false;

				if (target.startsWith("@")) {
					inelement = true;
					replaceex = "[\\s]+" + target.substring(1)
							+ "[\\s]*\\=[\\s]*\\\"[^\\\"]*\\\"";
					replacementval = " " + target.substring(1) + "=\""
							+ replacementval + "\"";
				} else if (target.equals("#value")) {
					replaceex = "\\>[^\\<]*\\<";
					replacementval = ">"+replacementval+"<";
				} else {
					continue;
				}

				template = template.replaceAll(replaceex, replacementval);
			}
		}
		else{
			template = with;
		}
		return template;
	}

}
